package com.gandong8.trace.tool.config.redis;

import com.gandong8.trace.tool.config.GlobalProperties;
import com.gandong8.trace.tool.config.redis.properties.RedissonProperties;
import com.gandong8.trace.tool.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Config;
import org.redisson.Redisson;
import org.redisson.RedissonClient;
import org.redisson.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({RedissonProperties.class, GlobalProperties.class})
@Slf4j
public class RedissonConf {

    @Autowired
    private RedissonProperties myProps;

    @Autowired
    private GlobalProperties globalProperties;

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnMissingBean(RedissonClient.class)
    public RedissonClient createClient() {
        if(!globalProperties.getRedissonOpen()) {
            System.err.println("redisson not allowed");
            return null;
        }
        Config config = createConfig();
        log.info("---redis start by redisson----");
        return Redisson.create(config);
    }

    private Config createConfig() {
        if (myProps == null) {
            throw new GlobalException("redisson config is null");
        }
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(myProps.getAddress())
                .setDatabase(myProps.getDatabase())
                .setTimeout(myProps.getTimeout())
                .setConnectTimeout(myProps.getConnectTimeout())
                .setIdleConnectionTimeout(myProps.getIdleConnectionTimeout())
                .setConnectionPoolSize(myProps.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(myProps.getConnectionMinimumIdleSize());
        if (StringUtils.isNotBlank(myProps.getPassword())) {
            serverConfig.setPassword(myProps.getPassword());
        }
        return config;
    }
}
